package common;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import wrapper.IFieldWrapper;

import com.csvreader.CsvReader;

/**
 * @author Or Kaplan
 * 
 * utils class
 */
public class Utils {
	private static final String EncodedChars = "0123456789_bcdfghjklmnpqrstvwxyz"; 
	public static final int CharSize = 5;
	public static final int MaxLength = 12;

	/**
	 * converts a freebase machine id into long unique id
	 * @param mid free base machine if
	 * @return long unique id
	 */
	public static long DecodeLongMid(String mid) {
		if (mid == null || mid.length() < 3) {
			throw new IllegalArgumentException("bad mid null or short");
		}
		
		long result = 0;
		String id = mid.substring(3);
		if (id.length() > MaxLength) {
			throw new IllegalArgumentException("id is too long");
		}

		for (int i = 0; i < id.length(); i++) {
			long decodedValue = EncodedChars.indexOf(id.charAt(i));
			result = (result << CharSize) | decodedValue;
		}
		return result;
	}
	
	/**
	 * remove duplicates on string array
	 * @param original - the original array
	 * @return unique items array
	 */
	public static String[] RemoveDuplicateString(String[] original)
	{
		Set<String> uniqueSet = new HashSet<String>(Arrays.asList(original));
		
		String[] uniques = new String[uniqueSet.size()];
        uniqueSet.toArray(uniques);
        return uniques;
	}
	
	/**
	 * opens and validates a CsvReader
	 * @param folder - working folder
	 * @param file - file name to open
	 * @param tables - tables using to validate
	 * @return CsvReader for the table
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static CsvReader OpenReader(String folder, String file, List<RelationTable> tables) throws FileNotFoundException, IOException
	{
		String tsvFile = String.format("%s%s%s.tsv", folder, System
				.getProperties().getProperty("file.separator"), file);

		CsvReader reader = new CsvReader(tsvFile, '\t', Charset.forName("UTF-8"));
		reader.setSafetySwitch(false);
		reader.readHeaders();
		
		for (RelationTable table : tables) {
			for (IFieldWrapper field : table.getFields()) {
				if (!Arrays.asList(reader.getHeaders()).contains(field.getTsvFieldName()))
				{
					reader.close();
					throw new IOException("field not found " + field.getTsvFieldName());
				}
			}
		}
		
		return reader;
	}
}
